#include "Trace.h"
#include "./capstone/capstone.h"
Trace::Trace(uc_engine * uc):
	uc(uc)
{
	uc_hook trace;
	uc_hook_add(uc, &trace, UC_HOOK_CODE, hook_code, nullptr, 1, 0);
}

Trace::~Trace()
{
}

void Trace::hook_code(uc_engine *uc, uint64_t address, uint32_t size, void *user_data)
{
	csh handle;
	cs_insn* insn;
	size_t count;
	size_t j;
	unsigned char code[300];
	uint32_t reg;
	uc_mem_read(uc, address, code, size);
	printf("0x%x:\t", address);
	uc_reg_read(uc, UC_ARM_REG_CPSR, &reg);
	if (reg & 0x20)
	{
		if (cs_open(CS_ARCH_ARM, CS_MODE_THUMB, &handle))
		{
			printf("ERROR: Failed to initialize engine!\n");
			return;
		}
	}
	else
	{
		if (cs_open(CS_ARCH_ARM, CS_MODE_ARM, &handle))
		{
			printf("ERROR: Failed to initialize engine!\n");
			return;
		}
	}
	count = cs_disasm(handle, code, size, address, 0, &insn);

	if (count)
	{
		for (j = 0; j < count; j++)
		{
			printf("%s\t\t%s  ", insn[j].mnemonic, insn[j].op_str);
		}
	}
	else
	{
		printf("error");
	}
	printf("\n");
	cs_close(&handle);
}